# # 通过type()函数来创建一个类
# Hello=type('Hello',  # 类名
#            (object,),# 父类
#            {
#             # 类属性、方法集合
#             '__init__':lambda self,name:setattr(self,'name',name),
#             '__str__':lambda self:self.name,
#             'sayHi':lambda self:print('say hi! %s'%self.name),
#             'cls_name':'class name hello'
#             }
# )

# h = Hello('Mike')
# Hello.cls_name = 'class name hello'
# h.age=18
# h.sayHi()
# print(h.age)
# print(h.cls_name)

# 使用type()创建类的方式等同于class定义一个类
# class Hello(object):
#     def __init__(self,name):
#         self.name = name
#     def __str__(self):
#         return self.name


# print(Hello('hello'))
# print(Hello('hello').name)
# print(Hello('hello').__class__)
# print(Hello('hello').__class__.__bases__)

# python内置的type就是一个元类
# class MyListMetaClass(type):
#     def __new__(cls, name, bases, attrs):
#         attrs['add']=lambda self,x:self.append(x)
#         return type.__new__(cls,name,bases,attrs)

# class MyList(list, metaclass=MyListMetaClass):
#     pass

# mylist=MyList()
# mylist.add(1)
# print(mylist)





class ModelMetaclass(type):
    def __new__(cls, name, bases, attrs):
        print('__new__ function in ModelMetaclass',f'name is {name}')
        if name=='Model':
            return type.__new__(cls, name, bases, attrs)
        print(f'Found model: {name}')
        mappings = dict()
        for k, v in attrs.items():
            print('Found mapping: %s ==> %s' % (k, v))
            mappings[k] = v
        # 为子类添加属性
        attrs['__mapping__']=mappings
        return type.__new__(cls, name, bases, attrs)


# m=ModelMetaclass('ModelMetaclass',(object,),{"k1":("name","Jobs")})
# print(m.__mapping__)

class Model(dict, metaclass=ModelMetaclass):
    def __init__(self, **kw):
        print('__init__ function in Model',f'kw is {kw}')
        super(Model, self).__init__(**kw)

    def __str__(self) -> str:
        return ' '.join(['%s:%s' % (k, self[k]) for k in self.keys()])
    

# m=Model(name='mike',age=18)
# print(m.__str__())

class User(Model):
    id = None
    name = None


m=User()
print(m.__mapping__)




